<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class TenantSetting extends Model
{
    use HasFactory;

    protected $fillable = [
        'tenant_id',
        'setting_key',
        'setting_value',
        'setting_type',
        'description'
    ];

    protected $casts = [
        'setting_value' => 'json'
    ];

    // 关联租户
    public function tenant()
    {
        return $this->belongsTo(Tenant::class);
    }

    // 设置类型常量
    const TYPE_STRING = 'string';           // 字符串
    const TYPE_INTEGER = 'integer';         // 整数
    const TYPE_BOOLEAN = 'boolean';         // 布尔值
    const TYPE_ARRAY = 'array';             // 数组
    const TYPE_JSON = 'json';               // JSON对象

    // 获取设置值（根据类型转换）
    public function getValueAttribute()
    {
        switch ($this->setting_type) {
            case self::TYPE_INTEGER:
                return (int) $this->setting_value;
            case self::TYPE_BOOLEAN:
                return (bool) $this->setting_value;
            case self::TYPE_ARRAY:
            case self::TYPE_JSON:
                return is_string($this->setting_value) ? json_decode($this->setting_value, true) : $this->setting_value;
            default:
                return $this->setting_value;
        }
    }

    // 设置值（根据类型处理）
    public function setValueAttribute($value)
    {
        switch ($this->setting_type) {
            case self::TYPE_ARRAY:
            case self::TYPE_JSON:
                $this->attributes['setting_value'] = is_array($value) ? json_encode($value) : $value;
                break;
            default:
                $this->attributes['setting_value'] = $value;
        }
    }

    // 获取租户设置
    public static function getTenantSetting($tenantId, $key, $default = null)
    {
        $setting = self::where('tenant_id', $tenantId)
                      ->where('setting_key', $key)
                      ->first();

        return $setting ? $setting->value : $default;
    }

    // 设置租户设置
    public static function setTenantSetting($tenantId, $key, $value, $type = self::TYPE_STRING, $description = null)
    {
        return self::updateOrCreate(
            ['tenant_id' => $tenantId, 'setting_key' => $key],
            [
                'setting_value' => $value,
                'setting_type' => $type,
                'description' => $description
            ]
        );
    }
}